package weaver.tools.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.entity.requestForm.ReqFlowFailMsgEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.jobs.common.DocUtil;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.webservices.WorkflowRequestTableRecord;
import weaver.workflow.webservices.WorkflowServiceImpl;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.*;

import static weaver.common.DateUtil.getDateTime;

/**
 * @Title: Ecology9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2021-09-15
 * @Description: 流程工具类
 * @ModifyLog:
 **/

public class WfUtil {


    private Map<String, Object> WorkflowCreateRequestId(User user, String formid, String isnextflow, Map<String, String> mainMap, List<Map<String, Object>> detailList) {
        BaseBean baseBean = new BaseBean();
        int seccategory = getDoccategory(formid);
        //主表数据
        ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
        List<WorkflowRequestTableField> mainData = new ArrayList<>();
        for (Map.Entry<String, String> entry : mainMap.entrySet()) {
            WorkflowRequestTableField field = new WorkflowRequestTableField();
            field.setFieldName(entry.getKey());
            field.setFieldValue(entry.getValue());
            if (isJSONArray(entry.getValue())) {
                String docids = "";
                JSONArray fileList = JSONArray.parseArray(entry.getValue());
                for (int l = 0; l < fileList.size(); l++) {
                    JSONObject fileJson = fileList.getJSONObject(l);
                    String filePath = Util.null2String(fileJson.getString("filePath"));
                    String fileName = Util.null2String(fileJson.getString("fileName"));
                    Map<String, Object> retMap = weaver.jobs.common.DocUtil.downloadByUrl(filePath);
                    if (Util.null2String(retMap.get("code")).equals("0")) {
                        String filepath = Util.null2String(retMap.get("data"));
                        baseBean.writeLog(">>>>>doCreateRequest>>>filepath=" + filepath);
                        int imagefileid = weaver.jobs.common.DocUtil.saveImageFile(fileName, filepath);
                        baseBean.writeLog(">>>>>doCreateRequest>>>imagefileid=" + imagefileid);
                        int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                        baseBean.writeLog(">>>>>doCreateRequest>>>docid=" + docid);
                        docids += "".equals(docids) ? docid : "," + docid;
                    }
                }
                field.setFieldValue(docids);
            }
            mainData.add(field);
        }
        requestParam.setMainData(mainData);
        //明细表数据
        if (!Objects.isNull(detailList)) {
            List<WorkflowDetailTableInfoEntity> detailData = new ArrayList<>();
            for (Map<String, Object> dtlmap : detailList) {
                String tablename = Util.null2String(dtlmap.get("tablename"));
                List<Map<String, String>> tableFieldList = (List<Map<String, String>>) dtlmap.get("tablefield");
                //设置明细信息
                WorkflowDetailTableInfoEntity detail1 = new WorkflowDetailTableInfoEntity();
                detail1.setTableDBName(tablename);
                //明细数据(多少条明细)
                WorkflowRequestTableRecord[] detailRows = new WorkflowRequestTableRecord[tableFieldList.size()];
                //遍历每一行明细
                int detailRowsIndex = 0;
                for (Map<String, String> map : tableFieldList) {
                    //明细行数据（每行有多少个字段）
                    WorkflowRequestTableField[] rowDatas = new WorkflowRequestTableField[map.size()];
                    int rowDatasIndex = 0;
                    //遍历明细每个字段
                    for (Map.Entry<String, String> detailMap : map.entrySet()) {
                        //行字段数据 （设置每个字段具体值）
                        WorkflowRequestTableField field1 = new WorkflowRequestTableField();
                        field1.setFieldName(detailMap.getKey());
                        field1.setFieldValue(detailMap.getValue());
                        if (isJSONArray(detailMap.getValue())) {
                            String docids = "";
                            JSONArray fileList = JSONArray.parseArray(detailMap.getValue());
                            for (int l = 0; l < fileList.size(); l++) {
                                JSONObject fileJson = fileList.getJSONObject(l);
                                String filePath = Util.null2String(fileJson.getString("filePath"));
                                String fileName = Util.null2String(fileJson.getString("fileName"));
                                Map<String, Object> retMap = weaver.jobs.common.DocUtil.downloadByUrl(filePath);
                                if (Util.null2String(retMap.get("code")).equals("0")) {
                                    String filepath = Util.null2String(retMap.get("data"));
                                    baseBean.writeLog(">>>>>doCreateRequest>>>filepath=" + filepath);
                                    int imagefileid = weaver.jobs.common.DocUtil.saveImageFile(fileName, filepath);
                                    baseBean.writeLog(">>>>>doCreateRequest>>>imagefileid=" + imagefileid);
                                    int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                    baseBean.writeLog(">>>>>doCreateRequest>>>docid=" + docid);
                                    docids += "".equals(docids) ? docid : "," + docid;
                                }
                            }
                            field1.setFieldValue(docids);
                        }
                        rowDatas[rowDatasIndex++] = field1;
                    }        //封装某行明细数据
                    WorkflowRequestTableRecord row1 = new WorkflowRequestTableRecord();
                    row1.setRecordOrder(0);
                    row1.setWorkflowRequestTableFields(rowDatas);
                    detailRows[detailRowsIndex++] = row1;
                }
                //封装所有明细数据
                detail1.setWorkflowRequestTableRecords(detailRows);
                detailData.add(detail1);
            }
            requestParam.setDetailData(detailData);
        }
        Map<String, Object> otherParams = new HashMap<>();
        otherParams.put("isnextflow", isnextflow);
        requestParam.setOtherParams(otherParams);
        //固定创建流程id
        Map<String, String> wf = getWorkflowId(formid);
        requestParam.setWorkflowId(Util.getIntValue(wf.get("workflowid")));
        requestParam.setRequestName(Util.null2String(wf.get("workflowname")) + "-" + user.getUsername() + "-" + getDateTime());
        WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
        PAResponseEntity paResponseEntity = operatePA.doCreateRequest(user, requestParam);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.putAll((Map<String, Object>) paResponseEntity.getData());
        PAResponseCode paResponseCode = paResponseEntity.getCode();
        resultMap.put("message", paResponseCode.getMessage());
        resultMap.put("statuscode", paResponseCode.getStatusCode() + "");
        ReqFlowFailMsgEntity flowFailMsgEntity = paResponseEntity.getReqFailMsg();
        resultMap.putAll(paResponseEntity.getErrMsg());
        resultMap.putAll(flowFailMsgEntity.getMsgInfo());
        return resultMap;
    }

    private Map<String, String> getWorkflowId(String formid) {
        RecordSet rs = new RecordSet();
        Map<String, String> resultMap = new HashMap<>();
        rs.executeQuery("select (case when activeversionid is null then id else activeversionid end) from workflow_base " +
                "where abs(formid)=? group by (case when activeversionid is null then id else activeversionid end) ", formid);
        rs.next();
        String workflowid = Util.null2String(rs.getString(1));
        resultMap.put("workflowid", workflowid);
        rs.executeQuery("select workflowname from workflow_base where id=?", workflowid);
        rs.next();
        String workflowname = Util.null2String(rs.getString(1));
        resultMap.put("workflowname", workflowname);
        return resultMap;
    }

    /**
     *@Description: 判断是否是json数组格式
     */
    private boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 获取附件上传目录ID
     */
    public int getDoccategory(String formid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select replace(doccategory,',','') from workflow_base where abs(formid)=?", formid);
        rs.next();
        return Util.getIntValue(rs.getString(1), -1);
    }

    /**
     * @param @param  creatorId    创建人Id
     * @param @param  workflowId   流程Id
     * @param @param  requestName  请求标题
     * @param @param  IsNextFlow   是否提交到下一节点
     * @param @param  requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: WorkflowCreateByMainTableMap
     */

    public String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, String> requestMainMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("-----创建流程传递的参数个数--------");
        baseBean.writeLog("creatorId:" + creatorId);
        baseBean.writeLog("workflowId:" + workflowId);
        baseBean.writeLog("requestName:" + requestName);
        baseBean.writeLog("IsNextFlow:" + IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if ("0".equals(IsNextFlow)) {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            baseBean.writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue());
            p++;
        }
        baseBean.writeLog("-----创建流程传递的参数个数p=" + p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                baseBean.writeLog("=======" + e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:" + requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            baseBean.writeLog("" + sbf.toString());
        } catch (Exception e) {
            baseBean.writeLog("错误：" + e);
        }
        return requestid;
    }

    //根据流程中字段名称获取字段对应的fieldid
    public static Map<String, String> getWfFieldId(int formid, String num) {
        formid = Math.abs(formid);
        String sql = "";
        if ("0".equals(num)) {
            sql = "select b.id,fieldname,detailtable from workflow_billfield b ,workflow_base a where b.billid=-"
                    + formid
                    + " and a.formid=b.billid and  (detailtable is null or detailtable = '') ";
        } else {
            sql = "select b.id,fieldname,detailtable from workflow_billfield b ,workflow_base a where b.billid=-"
                    + formid
                    + " and a.formid=b.billid and detailtable='formtable_main_"
                    + formid + "_dt" + num + "'";
        }
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        Map<String, String> array = new HashMap<String, String>();
        while (rs.next()) {
            array.put(Util.null2String(rs.getString("fieldname")).toLowerCase(), Util.null2String(rs.getString("id")));
        }
        return array;
    }

    //根据表名和字段名称获取字段fieldid
    public static String getWfFieldid(String formtable, String fieldname) {
        RecordSet rs = new RecordSet();
        String sql = "select concat('field',t1.id)as fieldid from workflow_billfield t1 \n" +
                "left join workflow_base t2 on t1.billid=t2.formid \n" +
                "where t1.fieldname=? and concat('formtable_main_',abs(t2.formid)) =?";
        rs.executeQuery(sql, fieldname, formtable);
        rs.next();
        String fieldid = Util.null2String(rs.getString("fieldid"));
        return fieldid;
    }

    // 根据流程请求ID 获取表名
    public static String getTableNameByRequestid(String requestid, String num) {
        String tableName = "";
        String table = "";
        RecordSet rs = new RecordSet();
        rs.execute("select t1.tablename from workflow_bill t1,workflow_base t2,workflow_requestbase t3 \n where t1.id =t2.formid and t2.id = t3.workflowid and t3.requestid = " + requestid);
        if (rs.next()) {
            table = Util.null2String(rs.getString("tablename"));
            if (num.equals("0")) {
                tableName = table;
            } else {
                tableName = table + "_dt" + num;
            }
        }
        return tableName;
    }

    // workflowid 流程ID获取表名
    public static String getTableNameByWfid(int workflowid) {
        String tableName = "";
        try {
            if (!"".equals(workflowid)) {
                String sql = "select t1.tablename from workflow_bill t1,workflow_base t2 where t1.id = t2.formid and t2.id = " + workflowid;
                RecordSet rs = new RecordSet();
                rs.executeQuery(sql);
                if (rs.next()) {
                    tableName = Util.null2String(rs.getString("tablename"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tableName;
    }

    // 流程自动提交--requestid 请求id/operator 流程操作者/结果 boolean型
    public static boolean autoSubmit(String requestid, int operator) {
        RequestService server = new RequestService();
        RequestInfo requestInfo = server.getRequest(Integer.parseInt(requestid));
        return server.nextNodeBySubmit(requestInfo, Integer.parseInt(requestid), operator, "");
    }

    // 获取流程数据集合 返回 map  里面存在一个主表 map(索引maindatamap)，每个明细表的List(索引dt1表示第一个明细，dt2表示第二个)
    //--requestid 请求ID/formid 表单id
    public static Map getRequestDataMap(String requestid, int formid) {
        Map<String, Object> requestMap = new HashMap<String, Object>();
        formid = Math.abs(formid);
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();

        String tablename = "";  //表名
        rs.execute("select tablename from workflow_bill where id=-" + formid);
        if (rs.next()) {
            tablename = rs.getString("tablename");
        }

        /*
         * 获取主表数据map
         */
        Map<String, String> mainDataMap = new HashMap<String, String>();
        rs.execute("select * from " + tablename + " where requestid = " + requestid);
        while (rs.next()) {
            //遍历所有字段
            String[] colnames = rs.getColumnName();
            for (String name : colnames) {
                name = name.toLowerCase();
                mainDataMap.put(name, Util.null2String(rs.getString(name)));
            }
        }
        requestMap.put("mainDataMap", mainDataMap);

        /*
         * 获取明细表数据map
         */
        rs.execute("select tablename,orderid from workflow_billdetailtable where billid=-" + formid);
        while (rs.next()) {
            String detailTableName = Util.null2String(rs.getString("tablename"));
            String orderid = Util.null2String(rs.getString("orderid"));
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            rs2.execute("select * from " + detailTableName + " where mainid=" + mainDataMap.get("id"));
            while (rs2.next()) {
                Map<String, String> detailDataMap = new HashMap<String, String>();
                //遍历所有字段
                String[] colnames = rs2.getColumnName();
                for (String name : colnames) {
                    name = name.toLowerCase();
                    detailDataMap.put(name, Util.null2String(rs2.getString(name)));
                }
                list.add(detailDataMap);
            }

            requestMap.put("dt" + orderid, list);
        }
        return requestMap;
    }

    //根据表单和字段获取下拉框值
    public static String getSelectItem(int billid, String fieldname, String selectvalue) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.selectvalue,t1.selectname from workflow_selectitem t1 left join workflow_billfield t2\n" +
                "on t1.fieldid=t2.id where abs(t2.billid)=? and t2.fieldname=? and t1.selectvalue=?";
        rs.executeQuery(sql, billid, fieldname, selectvalue);
        rs.next();
        String selectname = Util.null2String(rs.getString("selectname"));
        return selectname;
    }

    /**
     * @Description: 获取活跃版本号的workflowid
     */
    public static String getActiveWorkflowid(String formid) {
        RecordSet rs = new RecordSet();
        String workflowid = "";
        String sql = "select id,activeversionid,version from workflow_base where abs(formid)=?";
        rs.executeQuery(sql, formid);
        int count = rs.getCounts();
        while (rs.next()) {
            workflowid = count <= 1 ? Util.null2String(rs.getString("id")) : Util.null2String(rs.getString("activeversionid"));
        }
        return workflowid;
    }

    /**
     * @Description: 获取所有版本号的workflowid
     */
    public static String getWorkflowids(String formid) {
        RecordSet rs = new RecordSet();
        String workflowids = "";
        String sql = "select id from workflow_base where abs(formid)=?";
        rs.executeQuery(sql, formid);
        while (rs.next()) {
            String id = Util.null2String(rs.getString("id"));
            workflowids += "".equals(workflowids) ? id : "," + id;
        }
        return workflowids;
    }

    /**
     * 提交流程
     */
    public String submitWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.submitWorkflowRequest(null, requestid, userid, "submit", "由外部调用提交完成");
    }

    /**
     * 删除流程
     */
    public boolean deleteWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.deleteRequest(Util.getIntValue(requestid), Util.getIntValue(userid));
    }
    // 根据requestid获取主表id
    public String geIdByRequestid(String tablename,String requestid){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from "+tablename+" where requestid=?",requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取流程主表ID
     */
    public String getMainidByReq(String requestid, String formid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from formtable_main_" + formid + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
}
